package com.jcl.cloud.services.crawler.catchnew.task;


import com.alibaba.fastjson.JSON;
import com.jcl.cloud.common.service.util.PageOperation;
import com.jcl.cloud.services.crawler.catchnew.constant.TaskInfo;
import com.jcl.cloud.services.crawler.catchnew.model.CatchNewConfigModel;
import com.jcl.cloud.services.crawler.catchnew.service.RedisService;
import com.jcl.cloud.services.crawler.catchnew.util.SerializeUtils;
import com.jcl.cloud.services.crawler.catchnew.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class QcwyCatchNewHandler implements CatchNewHandler {

    private final static Logger logger = LoggerFactory.getLogger(QcwyCatchNewHandler.class);

    @Autowired
    private RedisService redisService;

    @Override
    public void execute(String crawlerId) {

        try {
            String catchNewConfig = this.redisService.hget("unicrawler:task:info:" + crawlerId, "catch-new-config");

            Map map = null;
            CatchNewConfigModel catchNewConfigModel = null;
            if(StringUtils.isBlank(catchNewConfig)){
               map = this.getMainKey(crawlerId);
               catchNewConfigModel = new CatchNewConfigModel();
               catchNewConfigModel.setConfig(map);
            }else {
                catchNewConfigModel = JSON.toJavaObject(JSON.parseObject(catchNewConfig),CatchNewConfigModel.class);
                map = catchNewConfigModel.getConfig();
            }


            //上传配置
            this.redisService.hset("unicrawler:task:info:" + crawlerId, "catch-new-config",JSON.toJSONString(catchNewConfigModel));


            this.doDownLoad(crawlerId,map);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            long currentTime = System.currentTimeMillis();
            long nextExecuteTime = currentTime + 180000 ;
            this.redisService.hset("unicrawler:task:info:"+crawlerId,"nextExecuteTime",String.valueOf(nextExecuteTime));
            //释放任务
            this.redisService.lpush("unicrawler:tasks:all", crawlerId);
        }
    }




    private Map<String,String> getMainKey(String crawlerId){

        Map map = new HashMap();

        String cookieStoreStr = this.redisService.hget("unicrawler:task:info:"+crawlerId, "cookieStore");

        BasicCookieStore cookieStore = SerializeUtils.serializeToObj(cookieStoreStr);
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);


        String Cookie = "";
        List<org.apache.http.cookie.Cookie> cookieList = context.getCookieStore().getCookies();


        // 更新CookieStore
        for (Cookie c : cookieList) {
            Cookie = Cookie + "; " + c.getName() + "=" + c.getValue();
        }

        String result = PageOperation.doInboxNavigator(context,Cookie);
        logger.info(String.format("任务号：%s   [1]=======>%s", crawlerId, result));
        String mainResult = PageOperation.doGet2InboxRecentEngine(context, 5);
        logger.info(String.format("任务号：%s   [2]=======>%s", crawlerId, mainResult));
        Map argsMap = new HashMap();
        argsMap.put("doType", "GetErrorContent");
        String otherResult = PageOperation.doGlobalInboxCommonAjax(argsMap, context);
        logger.info(String.format("任务号：%s   [3]=======>%s", crawlerId, otherResult));


        Document document = Jsoup.parse(mainResult);
        String __VIEWSTATE = document.getElementById("__VIEWSTATE").attr("value");
        String  hidAccessKey = document.getElementById("hidAccessKey").attr("value");

        map.put("__VIEWSTATE",__VIEWSTATE);
        map.put("hidAccessKey",hidAccessKey);

        return map;
    }



    private void doDownLoad(String crawlerId,Map<String,String> map){

        String taskId = crawlerId;
        String mainResult = "";
        try {
            String cookieStoreStr = this.redisService.hget("unicrawler:task:info:"+crawlerId, "cookieStore");

            BasicCookieStore cookieStore = SerializeUtils.serializeToObj(cookieStoreStr);
            HttpClientContext context = HttpClientContext.create();
            context.setCookieStore(cookieStore);

            logger.info(String.format("任务号：%s 开始执行下载任务>>>",crawlerId));
            //获取  未处理简历|未读
            String __VIEWSTATE = (String) map.get("__VIEWSTATE");
            String hidAccessKey = (String) map.get("hidAccessKey");
            logger.info(String.format("关键key值__VIEWSTATE = %s  ,  hidAccessKey = %s", __VIEWSTATE, hidAccessKey));

            Map argsMap = new HashMap<>();
            argsMap.put("__VIEWSTATE", __VIEWSTATE);
            argsMap.put("hidAccessKey", hidAccessKey);
            mainResult = PageOperation.doPost2InboxRecentEngine(argsMap, context, 5);
            logger.info(String.format("任务号：%s   [4]=======>%s", taskId, mainResult));

            //获取每个简历的value1、value2
            //获取简历结果
            Document document = Jsoup.parse(mainResult);
            List<Element> eleList = document.getElementsByAttributeValue("id", "chkBox");
            /*argsMap = new HashMap();
            argsMap.put("doType", "GetErrorContent");
            String result = PageOperation.doGlobalInboxCommonAjax(argsMap, context);
            logger.info(String.format("任务号：%s   [5]=======>%s", taskId, result));*/


            //点击全选
            String strKey = StringUtil.getStrWithRegex(mainResult, "var strKey = \"(.*?)\";");
            argsMap = new HashMap();
            argsMap.put("logType", "event");
            argsMap.put("pageNo", "24");
            argsMap.put("memo", "");
            argsMap.put("eventNo", "31");
            argsMap.put("Key", strKey);
            argsMap.put("rnd", Math.random());
            String result = PageOperation.doGlobalActionLogAjax(argsMap, context);
            logger.info(String.format("任务号：%s   [6]=======>%s", taskId, result));


            //点击导出简历
            argsMap = new HashMap();
            argsMap.put("doType", "GetDefaultFormat");
            result = PageOperation.doGlobalExportDivAjax(argsMap, context);
            logger.info(String.format("任务号：%s   [7]=======>%s", taskId, result));


            argsMap = new HashMap();
            argsMap.put("logType", "event");
            argsMap.put("pageNo", "24");
            argsMap.put("memo", "");
            argsMap.put("eventNo", "19");
            argsMap.put("Key", strKey);
            argsMap.put("rnd", Math.random());
            result = PageOperation.doGlobalActionLogAjax(argsMap, context);
            logger.info(String.format("任务号：%s   [8]=======>%s", taskId, result));


            argsMap = new HashMap();
            argsMap.put("doType", "GetOwnEmail");
            argsMap.put("t", "export");
            result = PageOperation.doGlobalInboxCommonAjax(argsMap, context);
            logger.info(String.format("任务号：%s   [9]=======>%s", taskId, result));


            //点击确定
            argsMap = new HashMap();
            argsMap.put("doType", "GetExportID");
            argsMap.put("type", "true");
            String ctmid_sgResult = PageOperation.doGlobalExportDivAjax(argsMap, context);
            logger.info("ctmid_sgResult :" + ctmid_sgResult);
            logger.info(String.format("任务号：%s   [10]=======>%s", taskId, result));

            argsMap = new HashMap();
            argsMap.put("doType", "EditMonitorLog");
            argsMap.put("downType", "Excel");
            argsMap.put("type", "true");
            result = PageOperation.doGlobalExportDivAjax(argsMap, context);
            logger.info(String.format("任务号：%s   [11]=======>%s", taskId, result));

            argsMap = new HashMap();
            String num = String.valueOf(Math.random());
            String lang = "";
            String ctmid_sg = "ctmid" + ctmid_sgResult.split("ctmid")[1].split("]]></message><")[0];
            String f = "EMP";
            String s = "";
            String j = "";

            String fa = "Excel";
            for (Element e : eleList) {
                TaskInfo.rid2jidMap.put(e.val(), e.attr("value2"));
                s += ("," + e.attr("value1"));
                j += ("," + e.attr("value2"));
            }


            String uuid = UUID.randomUUID().toString();

            argsMap.put("num", num);
            argsMap.put("lang", lang);
            argsMap.put("ctmid_sg", ctmid_sg);
            argsMap.put("f", f);
            argsMap.put("s", s.substring(1));
            argsMap.put("j", j.substring(1));
            argsMap.put("fa", fa);


            context.setCookieStore(null);
            result = PageOperation.doGet2Download(argsMap, context);
            logger.info(String.format("任务号：%s   [12]=======>%s", taskId, result));


            Document document2 = Jsoup.parse(result);
            String __VIEWSTATE2 = document2.getElementById("__VIEWSTATE").attr("value");
            String __VIEWSTATEGENERATOR = document2.getElementById("__VIEWSTATEGENERATOR").attr("value");
            String hidExportSeqID = document2.getElementById("hidExportSeqID").attr("value");
            String hidExportJobID = document2.getElementById("hidExportJobID").attr("value");
            String actionAttr = document2.getElementById("formExport").attr("action");
            String url = "http://cvs.ehire.51job.com" + actionAttr.substring(1).replaceAll("amp;", "").replaceAll("%2c", ",");
            String Referer = url;

            argsMap = new HashMap();
            argsMap.put("__VIEWSTATE", __VIEWSTATE2);
            argsMap.put("__VIEWSTATEGENERATOR", __VIEWSTATEGENERATOR);
            argsMap.put("hidExportSeqID", hidExportSeqID);
            argsMap.put("hidExportJobID", hidExportJobID);
            argsMap.put("url", url);
            argsMap.put("Referer", Referer);
            argsMap.put("uuid",uuid);

            PageOperation.doPost2Download(argsMap,TaskInfo.qcwyFileQueue,context);

            logger.info(String.format("任务号：%s   下载任务结束!",taskId));

        } catch (Exception e) {
            logger.error(String.format("任务号：%s  前程无忧doDownLoad发生异常：%s", taskId, e.getMessage()), e);
        }finally {
            try {
                Document document = Jsoup.parse(mainResult);
                String __VIEWSTATE = document.getElementById("__VIEWSTATE").attr("value");
                String  hidAccessKey = document.getElementById("hidAccessKey").attr("value");


                map.clear();
                map.put("__VIEWSTATE",__VIEWSTATE);
                map.put("hidAccessKey",hidAccessKey);

                CatchNewConfigModel catchNewConfigModel = new CatchNewConfigModel();
                catchNewConfigModel.setConfig(map);
                this.redisService.hset("unicrawler:task:info:" + crawlerId, "catch-new-config",JSON.toJSONString(catchNewConfigModel));
            } catch (Exception e) {
                logger.error(String.format("任务号：%s  上传catch-new-config发生异常：%s", taskId, e.getMessage()), e);
            }
        }
    }
}
